package com.kangdi.riggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kangdi.riggie.common.BaseContext;
import com.kangdi.riggie.common.Result;
import com.kangdi.riggie.entity.User;
import com.kangdi.riggie.service.UserService;
import com.kangdi.riggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("user")
@Slf4j
public class UserController {
    @Value("${spring.mail.username}")
    private String from;
    @Autowired
    private UserService userService;
    @Autowired
    private JavaMailSender mailSender;
    @PostMapping("sendMsg")
    public Result<String> sendMsg(@RequestBody User user, HttpSession session){
        String email = user.getEmail();
        String subject = "迅磊餐购登录验证码";
        if (StringUtils.isNotEmpty(email)){
            String code = ValidateCodeUtils.generateValidateCode4String(4);
            String context = "欢迎使用迅磊餐购，登录验证码为: " + code + ",五分钟内有效，请妥善保管!";
            log.info("code={}",code);
            userService.sendMsg(email,subject,context);
            session.setAttribute("code",code);
            return Result.success("验证码发送成功，请及时查看!");
        }
        return Result.success("验证码已发送");
    }
    @PostMapping("login")
    public Result<User> login(@RequestBody Map map,HttpSession session){
        String email = (String) map.get("email");
        String code = (String) map.get("code");
        Object inSessionCode = session.getAttribute("code");
        if (inSessionCode!=null&&inSessionCode.equals(code)){
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getEmail,email);
            User user = userService.getOne(queryWrapper);
            if (user==null){
                user=new User();
                user.setEmail(email);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            return Result.success(user);
        }
        return Result.error("验证码错误");
    }
    @PostMapping("loginout")
    public Result<String> loginout(HttpSession session){
        session.removeAttribute("user");
        return Result.success("退出成功");
    }
}
